import React, { useState } from 'react';
import { Card, Button, Typography, Divider, Tag, Table, Space, message } from 'antd';
import { LogoutOutlined, EyeOutlined, ReloadOutlined, CheckCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { logoutUser } from '../redux/features/userSlice';
import { useAuth } from '../hooks/useAuth';
import { parseJwt, isTokenExpired, getUserId, getUserRoles } from '../utils/jwtUtils';
import './JwtExamplePage.css';

const { Title, Text, Paragraph } = Typography;

const JwtExamplePage = () => {
  const dispatch = useDispatch();
  const { 
    isAuthenticated, 
    userInfo, 
    token, 
    isTokenAboutToExpire, 
    checkRole, 
    refreshAuthState 
  } = useAuth();
  
  const [showTokenDetails, setShowTokenDetails] = useState(false);
  const parsedToken = token ? parseJwt(token) : null;

  // 处理退出登录
  const handleLogout = async () => {
    try {
      await dispatch(logoutUser()).unwrap();
      message.success('退出登录成功');
      // 退出登录后跳转到登录页
      window.location.href = '/login';
    } catch (error) {
      message.error(error?.message || '退出登录失败');
    }
  };

  // 刷新认证状态
  const handleRefreshAuth = () => {
    refreshAuthState();
    message.success('认证状态已刷新');
  };

  // 切换显示token详情
  const toggleTokenDetails = () => {
    setShowTokenDetails(!showTokenDetails);
  };

  // 角色检查示例
  const hasAdminRole = checkRole('admin');
  const hasUserRole = checkRole('user');
  const hasManagerRole = checkRole(['manager', 'admin']); // 检查多个角色中的任意一个

  // token详情表格数据
  const tokenDetailsColumns = [
    {
      title: '字段名',
      dataIndex: 'field',
      key: 'field',
      width: '30%',
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
    },
  ];

  const tokenDetailsData = parsedToken ? (
    Object.entries(parsedToken).map(([field, value]) => ({
      key: field,
      field: field,
      value: typeof value === 'object' ? JSON.stringify(value) : String(value),
    }))
  ) : [];

  // 用户角色信息
  const userRoles = token ? getUserRoles(token) : null;
  const userId = token ? getUserId(token) : null;
  const tokenExpiration = parsedToken?.exp ? new Date(parsedToken.exp * 1000).toLocaleString() : 'N/A';

  return (
    <div className="jwt-example-container">
      <Title level={2}>JWT认证示例</Title>
      
      <Card title="认证状态" className="status-card">
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <div className="status-item">
            <Text strong>登录状态：</Text>
            <Tag color={isAuthenticated ? 'green' : 'red'}>
              {isAuthenticated ? '已登录' : '未登录'}
            </Tag>
          </div>
          
          {isAuthenticated && (
            <>
              <div className="status-item">
                <Text strong>用户信息：</Text>
                <Text>{userInfo?.username || userInfo?.phone || 'N/A'}</Text>
              </div>
              
              <div className="status-item">
                <Text strong>用户ID：</Text>
                <Text>{userId || 'N/A'}</Text>
              </div>
              
              <div className="status-item">
                <Text strong>用户角色：</Text>
                {Array.isArray(userRoles) ? (
                  userRoles.map((role, index) => (
                    <Tag key={index} color="blue" style={{ marginLeft: '8px' }}>{role}</Tag>
                  ))
                ) : (
                  <Tag color="blue" style={{ marginLeft: '8px' }}>{userRoles || 'N/A'}</Tag>
                )}
              </div>
              
              <div className="status-item">
                <Text strong>Token即将过期：</Text>
                <Tag color={isTokenAboutToExpire ? 'orange' : 'green'}>
                  {isTokenAboutToExpire ? (
                    <><ClockCircleOutlined /> 是 (5分钟内)</>
                  ) : (
                    <><CheckCircleOutlined /> 否</>
                  )}
                </Tag>
              </div>
              
              <div className="status-item">
                <Text strong>Token过期时间：</Text>
                <Text>{tokenExpiration}</Text>
              </div>
              
              <Button 
                type="primary" 
                danger 
                icon={<LogoutOutlined />} 
                onClick={handleLogout}
              >
                退出登录
              </Button>
            </>
          )}
          
          {!isAuthenticated && (
            <a href="/login" className="login-link">前往登录</a>
          )}
        </Space>
      </Card>

      <Divider />

      <Card title="角色检查示例" className="role-check-card">
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <Paragraph>以下是使用<code>checkRole()</code>方法检查不同角色权限的示例：</Paragraph>
          
          <div className="role-check-item">
            <Text strong>是否具有管理员角色：</Text>
            <Tag color={hasAdminRole ? 'green' : 'red'}>
              {hasAdminRole ? '是' : '否'}
            </Tag>
          </div>
          
          <div className="role-check-item">
            <Text strong>是否具有用户角色：</Text>
            <Tag color={hasUserRole ? 'green' : 'red'}>
              {hasUserRole ? '是' : '否'}
            </Tag>
          </div>
          
          <div className="role-check-item">
            <Text strong>是否具有管理员或经理角色：</Text>
            <Tag color={hasManagerRole ? 'green' : 'red'}>
              {hasManagerRole ? '是' : '否'}
            </Tag>
          </div>
        </Space>
      </Card>

      <Divider />

      {isAuthenticated && (
        <>
          <Card title="Token管理" className="token-management-card">
            <Space wrap>
              <Button 
                icon={<EyeOutlined />} 
                onClick={toggleTokenDetails}
              >
                {showTokenDetails ? '隐藏Token详情' : '查看Token详情'}
              </Button>
              
              <Button 
                icon={<ReloadOutlined />} 
                onClick={handleRefreshAuth}
              >
                刷新认证状态
              </Button>
            </Space>

            {showTokenDetails && token && (
              <div className="token-details">
                <Title level={4}>Token解析结果</Title>
                <Table 
                  columns={tokenDetailsColumns} 
                  dataSource={tokenDetailsData} 
                  pagination={false} 
                  size="small"
                  className="token-details-table"
                />
                
                <Title level={4}>原始Token</Title>
                <div className="token-string">
                  <pre>{token}</pre>
                </div>
              </div>
            )}
          </Card>

          <Divider />
        </>
      )}

      <Card title="JWT使用指南" className="guide-card">
        <Paragraph>本应用已集成完整的JWT认证系统，主要功能包括：</Paragraph>
        
        <ul>
          <li>自动在请求头中添加JWT Token</li>
          <li>Token过期前自动刷新</li>
          <li>401错误自动重试</li>
          <li>角色权限检查</li>
          <li>用户信息管理</li>
        </ul>

        <Paragraph>在组件中使用JWT相关功能：</Paragraph>
        
        <pre className="code-example">
{`import { useAuth, ProtectedRoute } from '../hooks/useAuth';

// 在组件中使用认证状态
const MyComponent = () => {
  const { isAuthenticated, userInfo, checkRole } = useAuth();
  
  // 检查是否具有特定角色
  const canAccessAdminFeatures = checkRole('admin');
  
  return (
    <>
      {isAuthenticated && <span>欢迎，{userInfo.username}</span>}
      {canAccessAdminFeatures && <AdminPanel />}
    </>
  );
};

// 使用ProtectedRoute保护页面
const ProtectedPage = () => {
  return (
    <ProtectedRoute roles="admin">
      <AdminContent />
    </ProtectedRoute>
  );
};`}
        </pre>
      </Card>
    </div>
  );
};

export default JwtExamplePage;